package com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.service.impl;

import cn.hutool.core.collection.CollectionUtil;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.zhjd.common.util.ZhjdIotUtils;
import com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.entity.AsphaltLowTemperatureElongationEntity;
import com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.entity.AsphaltLowTemperatureElongationResEntity;
import com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.mapper.AsphaltLowTemperatureElongationMapper;
import com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.service.AsphaltLowTemperatureElongationResService;
import com.ruoyi.zhjd.laboratory.modules.asphaltLowTemperatureElongation.service.AsphaltLowTemperatureElongationService;
import com.ruoyi.zhjd.laboratory.modules.errorRecord.service.ErrorRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("asphaltLowTemperatureElongationService")
public class AsphaltLowTemperatureElongationServiceImpl extends ServiceImpl<AsphaltLowTemperatureElongationMapper, AsphaltLowTemperatureElongationEntity> implements AsphaltLowTemperatureElongationService {

    @Autowired
    private AsphaltLowTemperatureElongationMapper asphaltLowTemperatureElongationMapper;

//    @Autowired
//    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private AsphaltLowTemperatureElongationResService asphaltLowTemperatureElongationResService;

    @Autowired
    private ErrorRecordService errorRecordService;

    private static Map<String,String> currentMap = new HashMap<>();

    /**
     * 列表
     */
    @Override
    public IPage<JSONObject> queryPage(Map<String, Object> params) {
//        IPage<AsphaltLowTemperatureElongationEntity> page = baseServiceComponent.getPage(params, AsphaltLowTemperatureElongationEntity.class);
        return asphaltLowTemperatureElongationMapper.queryPage(null, params);
    }

    /**
     * 信息
     *
     * @return AsphaltLowTemperatureElongationEntity
     */
    @Override
    public AsphaltLowTemperatureElongationEntity getInfo(String id) {
        return getById(id);
    }

    /**
     * 保存
     */
    @Override
    public void saveData(AsphaltLowTemperatureElongationEntity asphaltLowTemperatureElongation) {
        save(asphaltLowTemperatureElongation);
    }

    /**
     * 修改
     */
    @Override
    public void updateData(AsphaltLowTemperatureElongationEntity asphaltLowTemperatureElongation) {
        updateById(asphaltLowTemperatureElongation);
    }

    /**
     * 删除单条数据
     *
     * @param id
     */
    @Override
    public void deleteOneData(String id) {
        removeById(id);
    }

    /**
     * 删除
     */
    @Override
    public void deleteData(List<String> ids) {
        removeByIds(ids);
    }


    /**
     * 解析沥青低温延伸度试验仪数据
     * @param resData  试验结果数据
     * @param deviceId 试验设备id
     */
    @Override
    public void parsingData(String resData, String deviceId) {
        Date nowDate = new Date();
        try {
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(resData);
            //如果数据以00开头，可能设备刚开机或重启，表示一次新的实验开始
            if(StringUtils.equals(dataList.get(0),"00")){
                currentMap.remove(deviceId);
            }
            //验证位不进行校验
            int i = 4;
            //试验数据
            if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_TEST, dataList.get(i))) {
                AsphaltLowTemperatureElongationEntity entity = new AsphaltLowTemperatureElongationEntity();
                entity.setDeviceId(deviceId);
                if(currentMap.get(deviceId) == null){
                    AsphaltLowTemperatureElongationResEntity resEntity = new AsphaltLowTemperatureElongationResEntity();
                    resEntity.setDeviceId(deviceId);
                    asphaltLowTemperatureElongationResService.save(resEntity);
                    currentMap.put(deviceId,resEntity.getId());
                }
                //设置实验结果数据id
                entity.setResId(currentMap.get(deviceId));
                entity.setOriginalData(resData);
                entity.setCreateTime(nowDate);
                i++;
                entity.setFlag(dataList.get(i));

                // 将16进制转换为10进制数据，不含（0x）
                // 位移量Length1,Legth2,Legth3
                i++;
                BigDecimal length1 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                entity.setLength1(length1);
                i += 2;
                BigDecimal length2 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                entity.setLength2(length2);
                i += 2;
                BigDecimal length3 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                entity.setLength3(length3);
                i += 2;
                //延伸速率SPEED。 取值：10  50 表示为10mm/min 和50mm/min
                Integer speed1 = Integer.parseInt(dataList.get(i), 16);
                entity.setSpeed1(speed1);
                i++;
                Integer speed2 = Integer.parseInt(dataList.get(i), 16);
                entity.setSpeed2(speed2);
                i++;
                //温度 当前温度值CURR_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数 TODO:正负数处理
                //TODO
                entity.setCurrTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));
                //设定的温度值SET_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数。
                //TODO
                i += 2;
                entity.setSetTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));

                save(entity);
                //结果数据
            } else if (StringUtils.equals(ZhjdIotUtils.DATA_TYPE_RES, dataList.get(i))) {
                AsphaltLowTemperatureElongationResEntity resEntity = new AsphaltLowTemperatureElongationResEntity();
                resEntity.setId(currentMap.get(deviceId));
                currentMap.remove(deviceId);
                resEntity.setDeviceId(deviceId);
                resEntity.setOriginalData(resData);
                resEntity.setCreateTime(nowDate);
                // 将16进制转换为10进制数据，不含（0x）
                // 位移量Length1,Legth2,Legth3
                i++;
                BigDecimal length1 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                resEntity.setLength1(length1);
                i += 2;
                BigDecimal length2 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                resEntity.setLength2(length2);
                i += 2;
                BigDecimal length3 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
                resEntity.setLength3(length3);
                i += 2;
                //延伸速率SPEED。 取值：10  50 表示为10mm/min 和50mm/min
                Integer speed1 = Integer.parseInt(dataList.get(i), 16);
                resEntity.setSpeed1(speed1);
                i++;
                Integer speed2 = Integer.parseInt(dataList.get(i), 16);
                resEntity.setSpeed2(speed2);
                i++;
                //温度 当前温度值CURR_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数 TODO:正负数处理
                //TODO
                resEntity.setCurrTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));
                //设定的温度值SET_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数。
                //TODO
                i += 2;
                resEntity.setSetTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));
                asphaltLowTemperatureElongationResService.saveOrUpdate(resEntity);
            } else {
                throw new ServiceException("沥青低温延伸度数据解析异常：" + resData);
            }
        } catch (Exception e) {
            errorRecordService.saveErrorData(ZhjdIotUtils.ASPHALT_LOW_TEMPERATURE_ELONGATION,deviceId,resData);
            throw new ServiceException("数据解析异常");
        }
    }

    /**
     * 批处理历史数据,重新进行解析过程数据
     */
    public void reparseData(){
        //获取所有数据
        List<AsphaltLowTemperatureElongationEntity> list = asphaltLowTemperatureElongationMapper.selectList(new QueryWrapper<>());
        for(AsphaltLowTemperatureElongationEntity item : list){
            List<String> dataList = ZhjdIotUtils.analyzeExperimentalData(item.getOriginalData());
            int i = 4;
            AsphaltLowTemperatureElongationEntity entity = item;
            i++;
            entity.setFlag(dataList.get(i));

            // 将16进制转换为10进制数据，不含（0x）
            // 位移量Length1,Legth2,Legth3
            i++;
            BigDecimal length1 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
            entity.setLength1(length1);
            i += 2;
            BigDecimal length2 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
            entity.setLength2(length2);
            i += 2;
            BigDecimal length3 = ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1));
            entity.setLength3(length3);
            i += 2;
            //延伸速率SPEED。 取值：10  50 表示为10mm/min 和50mm/min
            Integer speed1 = Integer.parseInt(dataList.get(i), 16);
            entity.setSpeed1(speed1);
            i++;
            Integer speed2 = Integer.parseInt(dataList.get(i), 16);
            entity.setSpeed2(speed2);
            i++;
            //温度 当前温度值CURR_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数 TODO:正负数处理
            //TODO
            entity.setCurrTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));
            //设定的温度值SET_TEMP，高8位在前。2字节有符号整形，取值-32768~+32767，含1位小数。
            //TODO
            i += 2;
            entity.setSetTemp(ZhjdIotUtils.hexToDecimalism(dataList.get(i), dataList.get(i + 1)));
            updateById(entity);
        }
    }
    /**
     * 绑定材料
     * @param asphaltLowTemperatureElongationRes
     */
    public void changeSample(AsphaltLowTemperatureElongationResEntity asphaltLowTemperatureElongationRes){
        //更新试验结果表
        asphaltLowTemperatureElongationResService.updateById(asphaltLowTemperatureElongationRes);
        //查询试验过程数据
        List<AsphaltLowTemperatureElongationEntity> processList = list(new LambdaQueryWrapper<AsphaltLowTemperatureElongationEntity>().eq(AsphaltLowTemperatureElongationEntity::getResId,asphaltLowTemperatureElongationRes.getId()));
        if(CollectionUtil.isNotEmpty(processList)){
            for(AsphaltLowTemperatureElongationEntity item : processList){
                item.setSampleId(asphaltLowTemperatureElongationRes.getSampleId());
            }
           updateBatchById(processList);
        }
    }
}
